package presentation;

import java.io.IOException;

import javax.crypto.SecretKey;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Session;

import utils.DesEncrypter;

import db.DbUtils;

/**
 * Servlet implementation class AddUserServlet
 */
public class AddUserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String username = request.getParameter("username");
		String pass1 = request.getParameter("pass1");
		String pass2 = request.getParameter("pass2");
		
		//Check code
		
		String msg = request.getParameter("gencode"); 
        Object o = request.getSession().getAttribute("key");
        request.getSession().removeAttribute("key");
        SecretKey key = (SecretKey)o;
        DesEncrypter encrypter = new DesEncrypter(key);
        msg = encrypter.decrypt(msg);
        String code = request.getParameter("code");
        if (code != null && msg != null && code.equals(msg)) {

			if (username != null && pass1 != null && pass2 != null) {
				if (pass1.equals(pass2)) {
					Session hbsession = null;
					try {
						hbsession = DbUtils.startSession();
						DbUtils.addUser(hbsession, username, pass1);
						hbsession.getTransaction().commit();
						request.setAttribute("action", "done");
					} catch (Exception e) {
						hbsession.getTransaction().rollback();
					} finally {
						if (hbsession != null) {
							hbsession.close();
						}
					}
					request.getRequestDispatcher("register.jsp").forward(request, response);
				} else {
					response.sendRedirect("Error.jsp?msg=register");
				}
			} else {
				response.sendRedirect("Error.jsp?msg=register");
			}
        } else {
        	response.sendRedirect("Error.jsp?msg=register");
        }
	}

}
